import { defineStore } from 'pinia'
import { ref } from 'vue'
import { v4 as uuidv4 } from 'uuid';

export const useChatStore = defineStore('chat', {
    state: () => ({
        messages: [],
        isLoading: false,
        tokenCount: {
            total: 0,
            prompt: 0,
            completion: 0
        },
    }),

    actions: {
        // 新增方法：更新消息的Markdown内容
        updateMessageContent(messageId, content) {
            const index = this.messages.findIndex(m => m.id === messageId);
            if (index !== -1) {
            this.messages[index].content = content;
            this.messages[index].markdown = content; // 同步更新Markdown字段
            }
      },
        // 在消息对象中添加 type 字段
        addMessage(message) {
            const newMessage = {
              id: uuidv4(),
              timestamp: new Date().toISOString(),
              type: message.role === 'assistant' ? 'thinking' : 'normal',
              content: message.content || '', // 基础内容
              markdown: message.markdown || '', //带格式的内容
              reasoning: '',
              loading: message.role === 'assistant' ? true : false, // AI消息初始加载状态
              isStreaming: message.role === 'assistant' ? true : false, // 用户消息设为 false
              ...message // 包含 content、role 等字段
            };
            this.messages.push(newMessage);
            return newMessage.id; // 返回新消息的 id，而非数组长度！
        },

        // 更新指定消息的内容和类型
        updateMessage(messageId, updates){
            const index = this.messages.findIndex(msg => msg.id === messageId)
            if (index !== -1){
                this.messages[index] = { ...this.messages[index], ...updates};
            }
        },
        //更新最后一条消息内容（兼容旧逻辑）
        updateLastMessage(updates) {
            if (this.messages.length > 0) {
              const lastMessage = this.messages[this.messages.length - 1];
              // 使用传入的updates对象
              lastMessage.content = updates.content || lastMessage.content;
              lastMessage.markdown = updates.content || lastMessage.markdown;
              lastMessage.reasoning = updates.reasoning || lastMessage.reasoning
            //   lastMessage.loading = updates.loading !== undefined ? updates.loading : lastMessage.loading;
            //   lastMessage.loading = false; // 强制关闭 loading
              lastMessage.loading = updates.loading !== undefined ? updates.loading : lastMessage.loading; // 移除强制设为 false
              lastMessage.isStreaming = updates.isStreaming !== undefined ? updates.isStreaming : lastMessage.isStreaming; // 新增：同步 isStreaming
            //   lastMessage.type = lastMessage.loading ? 'thinking' : 'normal';
              lastMessage.type = 'normal'; // 确保类型正确
            }
          },

        //更新Token统计
        updateTokenCount(usage) {
            this.tokenCount.prompt += usage.prompt_tokens
            this.tokenCount.completion += usage.completion_tokens
            this.tokenCount.total += usage.total_tokens
        },
        // 清空消息
        clearMessages() {
            this.messages = []
        }
    },

    persist: {
        enabled: true,
        strategies: [
            {
                key: 'ai-chat-history',
                storage: null,
            },
        ],
    },
}) 